package com.ruoyi.project.sdi.sdiPaeaArc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.enums.WorkloadType;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.project.bms.bmsVoucherAssociate.domain.BmsVoucherAssociate;
import com.ruoyi.project.bms.bmsVoucherAssociate.service.IBmsVoucherAssociateService;
import com.ruoyi.project.paea.paeaDsTrade.service.IPaeaDsTradeService;
import com.ruoyi.project.sdi.sdiImage.domain.SdiImage;
import com.ruoyi.project.sdi.sdiImage.service.ISdiImageService;
import com.ruoyi.project.sdi.sdiPaeaArc.domain.SdiPaeaArc;
import com.ruoyi.project.sdi.sdiPaeaArc.enums.ArchivePaeaStatus;
import com.ruoyi.project.sdi.sdiPaeaArc.mapper.SdiPaeaArcMapper;
import com.ruoyi.project.sdi.sdiPaeaArc.model.SdiPaeaArcQueryRequest;
import com.ruoyi.project.sdi.sdiPaeaArc.service.ISdiPaeaArcService;
import com.ruoyi.project.stat.paeaReportWorkload.service.IStatisticsWorkloadService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 扫描批次Service业务层处理
 *
 * @author 关晓强
 * @date 2020-03-16
 */
@Service
public class SdiPaeaArcServiceImpl extends ServiceImpl<SdiPaeaArcMapper, SdiPaeaArc> implements ISdiPaeaArcService
{
    @Autowired
    private SdiPaeaArcMapper sdiPaeaArcMapper;

    @Autowired
    private ISdiImageService sdiImageService;

    @Autowired
    private IPaeaDsTradeService paeaDsTradeService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IBmsVoucherAssociateService bmsVoucherAssociateService;

    @Autowired
    private IStatisticsWorkloadService statisticsWorkloadService;
    /**
     * 查询扫描批次
     *
     * @param id 扫描批次ID
     * @return 扫描批次
     */
    @Override
    public SdiPaeaArc selectSdiPaeaArcById(String id)
    {
        return sdiPaeaArcMapper.selectSdiPaeaArcById(id);
    }

    /**
     * 查询扫描批次列表
     *
     * @param sdiPaeaArc 扫描批次
     * @return 扫描批次
     */
    @Override
    public List<SdiPaeaArc> selectSdiPaeaArcList(SdiPaeaArc sdiPaeaArc)
    {
        return sdiPaeaArcMapper.selectSdiPaeaArcList(sdiPaeaArc);
    }

    /**
     * 新增扫描批次
     *
     * @param sdiPaeaArc 扫描批次
     * @return 结果
     */
    @Override
    public int insertSdiPaeaArc(SdiPaeaArc sdiPaeaArc)
    {
        return sdiPaeaArcMapper.insertSdiPaeaArc(sdiPaeaArc);
    }

    /**
     * 修改扫描批次
     *
     * @param sdiPaeaArc 扫描批次
     * @return 结果
     */
    @Override
    public int updateSdiPaeaArc(SdiPaeaArc sdiPaeaArc)
    {
        return sdiPaeaArcMapper.updateSdiPaeaArc(sdiPaeaArc);
    }

    /**
     * 删除扫描批次对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteSdiPaeaArcByIds(String ids)
    {
        return sdiPaeaArcMapper.deleteSdiPaeaArcByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除扫描批次信息
     *
     * @param id 扫描批次ID
     * @return 结果
     */
    @Override
    public int deleteSdiPaeaArcById(String id)
    {
        return sdiPaeaArcMapper.deleteSdiPaeaArcById(id);
    }

    @Override
    @Transactional
    public void callBackSdiPaeaArc(SdiPaeaArc sdiPaeaArc) {
        // 第一步，获取批次
        sdiPaeaArc = this.getById(sdiPaeaArc.getId());
        int status = sdiPaeaArc.getStatus();
        // 根据批次ID，查询出批次对应的所有的影像实体
        List<SdiImage> sdiImages = sdiImageService.getSdiImagesBySdiPaeaArc(sdiPaeaArc);
        {
            int old_status = sdiPaeaArc.getStatus();

            // 回退到待OCR识别 待2次补录的回退 退到 手工补录
            if (old_status != ArchivePaeaStatus.Complete.getValue()
                    && old_status != ArchivePaeaStatus.WaitForceInput.getValue()) {

                //回退：修改影像流水关系表信息
                if(sdiImages!=null && !sdiImages.isEmpty()){
                    sdiImages.stream().forEach(sdiImage -> {
                        sdiImage.setDescription(null);
                        sdiImage.setParentId(null);
                        sdiImage.setType(null);
                        sdiImage.setPageIndex(sdiImage.getIndexNo());
                        sdiImage.setOcrResult(null);
                        sdiImage.setCompStatus("0");
                        sdiImage.setStatus(0);
                        sdiImage.setCompTradeId(null);
                        sdiImage.setCompTxnSeq(null);
                    });
                    sdiImageService.updateBatchById(sdiImages);
                }

                //回退：流水相关
                paeaDsTradeService.deleteTradeImageRelBySdiPaeaArc(sdiPaeaArc);

                //回退：批次信息
                sdiPaeaArc.setOcrServerId(null);
                sdiPaeaArc.setStatus(200);
                sdiPaeaArc.setInputer("");
                sdiPaeaArc.setLocker("");
                sdiPaeaArc.setOcrRate(null);
                sdiPaeaArc.setInputTime(null);
                this.saveOrUpdate(sdiPaeaArc);
                //todo 回退：修改统计OCR信息
//            String brCode = sdiPaeaArc.getOrgCode();
//            String trTeller = sdiPaeaArc.getTellerCode();
//            Date trDate = sdiPaeaArc.getTrDate();
//            List<PaeaReportStatOcr> paeaReportStatOcrs = (List) this.servicePaeaReportStatOcrImpl
//                    .findPaeaReportStatOcr(trDate, brCode, trTeller);
//            if (paeaReportStatOcrs != null && paeaReportStatOcrs.size() > 0)
//                for (PaeaReportStatOcr paeaReportStatOcr : paeaReportStatOcrs) {
//                    servicePaeaReportStatOcrImpl
//                            .deletePaeaReportStatOcrByPrimaryId(paeaReportStatOcr
//                                    .getBatchNo());
//                }
            }

            // 勾对完成状态只能回退到待手工补录状态 800-->400
            if (old_status == ArchivePaeaStatus.Complete.getValue()
                    || old_status == ArchivePaeaStatus.WaitForceInput.getValue()) {
                // 修改批次表的状态
                sdiPaeaArc.setStatus(ArchivePaeaStatus.WaitDataInput.getValue());
                this.saveOrUpdate(sdiPaeaArc);
            }
        }
    }

    /**
     * 回退批次至指定人员
     *
     * @param sdiPaeaArcQueryRequest 扫描批次
     * @return 结果
     */
    @Override
    public void callBackSdiPaeaArcToUser(SdiPaeaArcQueryRequest sdiPaeaArcQueryRequest) {
        // 第一步，获取批次
        SdiPaeaArc sdiPaeaArc = this.getById(sdiPaeaArcQueryRequest.getId());

        //判断用户状态
        User user = userService.selectUserByLoginName(sdiPaeaArcQueryRequest.getCallBackToInputer());
        if(user == null || !UserConstants.NORMAL.equals(user.getStatus())){
            //用户不存在或为停用，退回至待获取状态
            sdiPaeaArc.setStatus(ArchivePaeaStatus.toArcBatchStatus(
                    sdiPaeaArc.getStatus()).getUnlockStatus().getValue());
        } else {
            //存在并生效状态，退回至已获取状态
            if(sdiPaeaArc.getStatus() == ArchivePaeaStatus.Complete.getValue()){
                sdiPaeaArc.setStatus(ArchivePaeaStatus.正在重新补录795.getValue());
            }
        }
        sdiPaeaArc.setLocker(sdiPaeaArcQueryRequest.getCallBackToInputer());
        sdiPaeaArc.setInputer(sdiPaeaArcQueryRequest.getCallBackToInputer());
        this.saveOrUpdate(sdiPaeaArc);
    }

    @Override
    @Transactional
    public void removeArc(String ids) {
        User user = ShiroUtils.getSysUser();
        //回退登记信息的扫描状态
        SdiPaeaArc sdiPaeaArc = this.getById(ids);
        //todo 删除还需判断实物档案状态
        callBackBmsVoucherAssociateByRemoveArc(sdiPaeaArc);
        //删除批次时删除对应工作量
        Date workDate = new java.util.Date(System.currentTimeMillis());
        statisticsWorkloadService.deleteLogWorkload(user, workDate, WorkloadType.扫描, sdiPaeaArc.getFrontNum());
        //删除批次
        this.removeById(ids);
    }

    /**
     * 回退登记信息的扫描状态
     * @param sdiPaeaArc
     */
    private void callBackBmsVoucherAssociateByRemoveArc(SdiPaeaArc sdiPaeaArc) {
        BmsVoucherAssociate bmsVoucherAssociate = this.bmsVoucherAssociateService.getOne(new QueryWrapper<BmsVoucherAssociate>()
                .eq("tr_date",sdiPaeaArc.getTrDate())
                .eq("org_code",sdiPaeaArc.getOrgCode())
                .eq("teller_code",sdiPaeaArc.getTellerCode()));
        bmsVoucherAssociate.setScanNum(0);
        bmsVoucherAssociate.setScanStatus(0);
        this.bmsVoucherAssociateService.updateBmsVoucherAssociate(bmsVoucherAssociate);
    }
}
